package com.dt.common.validation.definition;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;

import com.dt.common.validation.annotation.Size;
import com.dt.common.validation.impl.DefaultValidationDefinition;
import com.dt.common.validation.itf.ConstraintValidation;
import com.dt.common.validation.itf.ValidationContext;

import lombok.Setter;

@Setter
public class SizeDefinition extends DefaultValidationDefinition {

	private int min;
	private int max;

	public SizeDefinition() {
		this.name = Size.class.getSimpleName();
	}

	@Override
	protected void fillMsgInterpolatingParams(Map<String, String> params) {
		params.put("min", Integer.valueOf(min).toString());
		params.put("max", Integer.valueOf(max).toString());
	}

	@Override
	public ConstraintValidation buildValidation() {

		return new ConstraintValidation() {

			@Override
			public boolean isValid(ValidationContext context, Object objectValue, Object propertyValue) {
				if (propertyValue == null) {
					return true;
				}

				Integer len = null;

				if (propertyValue instanceof CharSequence) {
					len = ((CharSequence) propertyValue).length();

				} else if (propertyValue instanceof Collection) {
					len = ((Collection<?>) propertyValue).size();

				} else if (propertyValue instanceof Map<?, ?>) {
					len = ((Map<?, ?>) propertyValue).size();

				} else if (propertyValue.getClass().isArray()) {
					len = Array.getLength(propertyValue);

				}

				if (len == null) {
					return false;

				} else if (min <= len && len <= max) {
					return true;
				}
				return false;
			}

		};

	}

}
